package controllers;

//import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
import static play.data.Form.form;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import models.Passwords;
import models.User;
import play.*;
import play.data.Form;
import play.db.ebean.Model;
import play.mvc.*;
import views.html.*;
import play.libs.Json;

public class Application extends Controller {
	
    public static class Login {
        
        public String name;
        public String password;
     }

	static User admin = null;
	
	public static Result index() throws NoSuchAlgorithmException {
		session().clear();
		if (User.isnull()) {
			
				admin = new User();
				admin.name = "admin";
				admin.password = Passwords.encode("latwehaslo12");
				admin.nr_karty=Passwords.encode("883330027");
				admin.save();
				admin = null;
				admin = new User();
				admin.name = "admin2";
				admin.password = Passwords.encode("latwehaslo21");
				admin.nr_karty=Passwords.encode("756392346");
				admin.save();
				admin = null;
				admin = new User();
				admin.name = "admin3";
				admin.password = Passwords.encode("latwiejszehaslo12");
				admin.nr_karty=Passwords.encode("39867285");
				admin.save();
			
		}
		return ok(index.render("Your new application is ready."));
	}
	public static Result login() throws NoSuchAlgorithmException {
		session().clear();
		
		  Form<Login> loginForm = form(Login.class).bindFromRequest();
	        if(loginForm.hasErrors()) {
	            return badRequest(index.render("error"));
	        } 
		//User usr = Form.form(User.class).bindFromRequest().get();
		
		try{if (Passwords.check(loginForm.get().password, User.checkUser(loginForm.get().name).password)) {
			session("password", loginForm.get().password);
			return redirect(routes.dahsboard.index());

		}}
		catch(NullPointerException ex){
			return badRequest(index.render("error"));
		}
		return badRequest(index.render("error"));
	}
	


}
